package org.serverct.finalfight.game.uhc.team;

import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.serverct.finalfight.internal.game.basic.BasicGame;
import org.serverct.finalfight.internal.game.basic.BasicGamer;
import org.serverct.finalfight.internal.game.basic.GameType;
import org.serverct.finalfight.internal.info.SimpleInfoHandler;
import org.serverct.finalfight.util.StringPair;

import java.util.HashSet;
import java.util.UUID;

public class UHCTeamGame extends BasicGame {
    public int maxPerTeam;
    public HashSet<Team> teams = new HashSet<>();

    public UHCTeamGame(YamlConfiguration yaml) {
        super(yaml);
        this.maxPerTeam = yaml.getInt("maxperteam");
        this.type = GameType.UHC_TEAM;
    }

    @Override
    public void afterInit() {
        Team tmp = new Team(TeamType.BLUE);
        if (players.size() > maxPerTeam) {
            //人数较充足
            int average = (int) Math.ceil(players.size() / maxPerTeam);
            for (UUID uuid : players.keySet()) {
                BasicGamer gamer = players.get(uuid);
                TeamPlayer newGamer = new TeamPlayer(gamer.isAlive, tmp, uuid);

                players.put(uuid, newGamer);

                if (tmp.getAmount() >= average) {
                    teams.add(tmp);
                    tmp = new Team(tmp.type.next());
                }
            }
        } else {
            //人数不足
            for (UUID uuid : players.keySet()) {
                BasicGamer gamer = players.get(uuid);
                TeamPlayer newGamer = new TeamPlayer(gamer.isAlive, tmp, uuid);

                players.put(uuid, newGamer);

                teams.add(tmp);
                tmp = new Team(tmp.type.next());
            }
        }
        //发送信息
        for (UUID uuid : players.keySet()) {
            Player player = Bukkit.getPlayer(uuid);

            StringPair replacer_1 = new StringPair("%team%", getTeam(player).type.getColoredName());
            StringPair replacer_2 = new StringPair("%mates%", getTeam(player).getMates());

            SimpleInfoHandler.sendTitle(player, "jointeam.title", "jointeam.subtitle", replacer_1);
            for (int i = 1; i <= 4; i++) {
                SimpleInfoHandler.sendMessage(player, false,
                        "jointeam.message_" + i,
                        replacer_1, replacer_2);
            }
        }
    }

    public Team getTeam(Player player) {
        for (Team team : teams) {
            if (team.players.containsKey(player.getUniqueId())) {
                return team;
            }
        }
        return null;
    }

    @Override
    public void afterEnd() {
    }
}
